﻿using System;
using System.Data;
using System.Globalization;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using ContractManagementSystem.BusinessLogic;

namespace ContractManagementSystem
{
    public partial class PageReportTimesheet : System.Web.UI.Page
    {
        const string AdminRole = "Admin";
        const string LineManagerRole = "LineManager";
        const string ContractorRole = "Contractor";
        const string ConsultantRole = "Consultant";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitialPage();
            }
        }

        private void BindList()
        {
            if (Session["Name"] != null)
            {
                string userName = Session["Name"].ToString();
                string role = UserBusiness.FetchRoleByUserName(userName);

                if (ContractDropDownList.SelectedIndex != 0 && ContractDropDownList.Items.Count > 0 &&
                    !string.IsNullOrEmpty(FromDateTextBox.Text) && !string.IsNullOrEmpty(ToDateTextBox.Text))
                {
                    DataTable source;
                    DateTime fromDate = Convert.ToDateTime(FromDateTextBox.Text, CultureInfo.CurrentCulture);
                    DateTime toDate = Convert.ToDateTime(ToDateTextBox.Text, CultureInfo.CurrentCulture);
                    string status = StatusDropDownList.SelectedItem.Value;
                    var contractId = new Guid(ContractDropDownList.SelectedItem.Value);

                    switch (role)
                    {
                        case AdminRole:
                            var contractorIdForAdmin = new Guid(UserBusiness.FetchContractorIdByUserName(ContractorTextBox.Text).Rows[0][0].ToString());
                          
                            source = TimesheetBusiness.TimesheetSearch(fromDate, toDate, contractId,
                                                                       contractorIdForAdmin, status);
                            TimesheetListView.DataSource = source;
                            TimesheetListView.DataBind();
                            Session["ReportTimesheet"] = TimesheetBusiness.TimesheetSearch(fromDate, toDate, contractId,
                                                                       contractorIdForAdmin, status);

                            break;
                        case LineManagerRole:
                            var contractorIdForLineManager = new Guid(ContractorDropDownList.SelectedItem.Value);
                            source = TimesheetBusiness.TimesheetSearch(fromDate, toDate, contractId,
                                                                       contractorIdForLineManager, status);
                            TimesheetListView.DataSource = source;
                            TimesheetListView.DataBind();
                            Session["ReportTimesheet"] = TimesheetBusiness.TimesheetSearch(fromDate, toDate, contractId,
                                                                       contractorIdForLineManager, status);

                            if (source.Rows.Count > 0)
                            {
                                foreach (var listViewDataItem in TimesheetListView.Items)
                                {
                                    var actionPanel = listViewDataItem.FindControl("ActionPanel") as Panel;
                                    actionPanel.Visible = false;
                                }
                            }

                            break;
                        case ContractorRole:
                            var contractorId = new Guid(UserBusiness.FetchIdByUserName(Session["Name"].ToString()));
                            source = TimesheetBusiness.TimesheetSearch(fromDate, toDate, contractId,
                                                                       contractorId, status);
                            Session["ReportTimesheet"] = TimesheetBusiness.TimesheetSearch(fromDate, toDate, contractId,
                                                                       contractorId, status);
                            TimesheetListView.DataSource = source;
                            TimesheetListView.DataBind();

                            if (source.Rows.Count > 0)
                            {
                                foreach (var listViewDataItem in TimesheetListView.Items)
                                {
                                    var statusPanel = listViewDataItem.FindControl("StatusPanel") as Panel;
                                    statusPanel.Visible = false;
                                }
                            }

                            break;
                        case ConsultantRole:
                            var contractorIdForConsultant = new Guid(ContractorDropDownList.SelectedItem.Value);
                            source = TimesheetBusiness.TimesheetSearch(fromDate, toDate, contractId,
                                                                       contractorIdForConsultant, status);
                            TimesheetListView.DataSource = source;
                            TimesheetListView.DataBind();
                            Session["ReportTimesheet"] = TimesheetBusiness.TimesheetSearch(fromDate, toDate, contractId,
                                                                       contractorIdForConsultant, status);

                            if (source.Rows.Count > 0)
                            {
                                var headerActionPanel = TimesheetListView.FindControl("HeaderActionPanel") as Panel;
                                headerActionPanel.Visible = false;
                                var headerConsultantPanel = TimesheetListView.FindControl("HeaderConsultantPanel") as Panel;
                                headerConsultantPanel.Visible = false;
                                foreach (var listViewDataItem in TimesheetListView.Items)
                                {
                                    var statusPanel = listViewDataItem.FindControl("StatusPanel") as Panel;
                                    statusPanel.Visible = false;
                                    var actionPanel = listViewDataItem.FindControl("ActionPanel") as Panel;
                                    actionPanel.Visible = false;
                                    var consultantPanel = listViewDataItem.FindControl("ConsultantPanel") as Panel;
                                    consultantPanel.Visible = false;
                                }
                            }

                            break;
                    }
                    ContractDropDownList.DataBind();
                }
            }
        }

        private void BindContractor()
        {
            string userName = Session["Name"].ToString();
            var keyId = new Guid(UserBusiness.FetchProfileByUserName(userName).Rows[0][0].ToString());
            string role = UserBusiness.FetchRoleByUserName(userName);
            char key = role.Equals(LineManagerRole) ? 'L' : 'C';
            
            ContractorDropDownList.DataSource = ContractBusiness.FetchContractorByKey(keyId, key);
            Session["ReportTimesheet"] = ContractBusiness.FetchContractorByKey(keyId, key);
            ContractorDropDownList.DataValueField = "ContractorId";
            ContractorDropDownList.DataTextField = "FullName";
            ContractorDropDownList.DataBind();
            ContractorDropDownList.Items.Insert(0, "-- Choose item --");
        }

        private void InitialPage()
        {
            if (Session["Name"] != null)
            {
                string userName = Session["Name"].ToString();
                string role = UserBusiness.FetchRoleByUserName(userName);
                Session["ReportTimesheet"] = UserBusiness.FetchRoleByUserName(userName);
                roleBox.Value = role;
                switch (role)
                {
                    case AdminRole:
                        AdminAction.Visible = true;
                        ContractorDropDownList.Visible = false;
                        break;
                    case ConsultantRole:
                        BindContractor();
                        ContractorDropDownList.Visible = true;
                        ContractorDropDownList.SelectedIndex = 0;
                        break;
                    case ContractorRole:
                        AdminAction.Visible = true;
                        ContractorSelectButton.Visible = false;
                        ContractorDropDownList.Visible = false;
                        ContractDropDownList.DataSource = ContractBusiness.FetchByContractorId(UserBusiness.FetchIdByUserName(Session["Name"].ToString()));
                        Session["ReportTimesheet"] = ContractBusiness.FetchByContractorId(UserBusiness.FetchIdByUserName(Session["Name"].ToString()));
                        ContractDropDownList.DataValueField = "ContractId";
                        ContractDropDownList.DataTextField = "Name";
                        ContractDropDownList.DataBind();
                        ContractDropDownList.Items.Insert(0, "-- Choose item --");
                        ContractorTextBox.Enabled = false;
                        ContractorTextBox.Text = userName;
                        break;
                    case LineManagerRole:
                        BindContractor();
                        ContractorDropDownList.Visible = true;
                        break;
                }
            }
        }

        protected void TimesheetDataPager_OnPreRender(object sender, EventArgs e)
        {
            BindList();
        }

        protected void ContractorSelectButton_OnClick(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(ContractorTextBox.Text))
            {
                var contractorIdSource = UserBusiness.FetchContractorIdByUserName(ContractorTextBox.Text);
               
                if (!string.IsNullOrEmpty(UserBusiness.ErrorMessage) || contractorIdSource.Rows.Count == 0)
                {
                    CheckContractorLiteral.Visible = true;
                    ContractDropDownList.Items.Clear();
                    TopPanel.Visible = false;
                    //ActionTopPanel.Visible = false;
                }
                else
                {
                    string contractorId = contractorIdSource.Rows[0][0].ToString();
                    CheckContractorLiteral.Visible = false;
                    ContractDropDownList.DataSource = ContractBusiness.FetchByContractorId(contractorId);
                
                    ContractDropDownList.DataValueField = "ContractId";
                    ContractDropDownList.DataTextField = "Name";
                    ContractDropDownList.DataBind();
                    ContractDropDownList.Items.Insert(0, "-- Choose item --");
                }
            }
            else
            {
                CheckContractorLiteral.Visible = true;
                ContractDropDownList.Items.Clear();
                TopPanel.Visible = false;
                //ActionTopPanel.Visible = false;
            }
        }

        protected void ContractorDropDownList_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            if (ContractorDropDownList.SelectedIndex != 0)
            {
                var contractorId = new Guid(ContractorDropDownList.SelectedItem.Value);

                string userName = Session["Name"].ToString();
                var keyId = new Guid(UserBusiness.FetchProfileByUserName(userName).Rows[0][0].ToString());
                string role = UserBusiness.FetchRoleByUserName(userName);
                Session["ReportTimesheet"] = UserBusiness.FetchRoleByUserName(userName);
                char key = role.Equals(LineManagerRole) ? 'L' : 'C';

                ContractDropDownList.DataSource = ContractBusiness.FetchContractByKey(contractorId, keyId, key);
                Session["ReportTimesheet"] = ContractBusiness.FetchContractByKey(contractorId, keyId, key);
                ContractDropDownList.DataValueField = "ContractId";
                ContractDropDownList.DataTextField = "Name";
                ContractDropDownList.DataBind();
                ContractDropDownList.Items.Insert(0, "-- Choose item --");
            }
            else
            {
                ContractDropDownList.Items.Clear();
            }
        }

        protected void ContractDropDownList_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            if (ContractDropDownList.SelectedIndex != 0)
            {
                var contractId = new Guid(ContractDropDownList.SelectedItem.Value);
                var source = ContractBusiness.FetchContractDateById(contractId);
                Session["ReportTimesheet"] = ContractBusiness.FetchContractDateById(contractId);
                FromDateTextBox.Text = Convert.ToDateTime(source.Rows[0]["StartDate"], CultureInfo.CurrentCulture).ToShortDateString();
                ToDateTextBox.Text = Convert.ToDateTime(source.Rows[0]["EndDate"], CultureInfo.CurrentCulture).ToShortDateString();
            }
            else
            {
                FromDateTextBox.Text = "";
                ToDateTextBox.Text = "";
                TopPanel.Visible = false;
                //ActionTopPanel.Visible = false;
            }
        }

        protected void ListTimesheetButton_OnClick(object sender, EventArgs e)
        {
            if (ContractDropDownList.SelectedIndex != 0 && ContractorDropDownList.SelectedIndex != 0 &&
                !string.IsNullOrEmpty(FromDateTextBox.Text) && !string.IsNullOrEmpty(ToDateTextBox.Text))
            {
                BindList();
                TopPanel.Visible = true;
            }
            else
            {
                TopPanel.Visible = false;
            }
        }

        protected void TimesheetListView_OnItemDataBound(object sender, ListViewItemEventArgs e)
        {
            Label rejectStatus;
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                rejectStatus = e.Item.FindControl("StatusLabel") as Label;
                if (rejectStatus.Text.Equals("Reject"))
                {
                    rejectStatus.CssClass = "forReject";
                    var itemCheckBox = e.Item.FindControl("ItemCheckBox") as HtmlInputCheckBox;
                    var timesheetId = new Guid(itemCheckBox.Value.Split('$')[0]);
                    string reasonMessage = TimesheetBusiness.FetchReasonByTimesheetId(timesheetId).Rows[0]["Reason"].ToString();
                    rejectStatus.ToolTip = reasonMessage;
                }
            }
        }   

        protected void ReportButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/ReportTimesheet.aspx");
        }

        protected void StatusDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindList();
        }
    }
}
